package com.hotel.hotelsystem.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hotel.hotelsystem.mapper.HotelInfoMapper;
import com.hotel.hotelsystem.mapper.HotelListMapper;
import com.hotel.hotelsystem.pojo.HotelInfo;
import com.hotel.hotelsystem.pojo.HotelList;
import com.hotel.hotelsystem.service.HotelIndexRankingListService;
import com.hotel.utils.MapUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

@Service
public class HotelIndexRankingListServiceImpl implements HotelIndexRankingListService {

    @Autowired
    private HotelInfoMapper hotelInfoMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private HotelListMapper hotelListMapper;

    /**
     * 1.查询出 mysql 当中所有的酒店id
     * 2.遍历 list 并查出 redis 当中所有酒店的收藏数量
     * 3.对 map 进行降序排序
     * 4.去 mysql 当中查询 hotel_list 当中对应的酒店
     * @param num 取排行前多少名
     */
    @Override
    public List<HotelList> rankingList(Integer num) {
        //1.查询出 mysql 当中所有的酒店id
        List<HotelInfo> hotelInfos = hotelInfoMapper.selectList(null);
        Map<Integer, Long> map = new TreeMap<>();
        //2.遍历 list 并查出 redis 当中所有酒店的收藏数量
        for (HotelInfo hotelInfo : hotelInfos) {
            String hotel = "hotel:"+hotelInfo.getHotelId();
            map.put(hotelInfo.getHotelId(),redisTemplate.opsForSet().size(hotel));
        }
        //3.对 map 进行降序排序
        Map<Integer, Long> map1 = MapUtil.sortDescend(map);
        int count = 0;
        ArrayList<HotelList> list = new ArrayList<>();
        for (Map.Entry<Integer, Long> integerLongEntry : map1.entrySet()) {
            if (count < num){
//                System.out.println(integerLongEntry.getKey()+":"+map.get(integerLongEntry.getKey()));
                //4.去 mysql 当中查询 hotel_list 当中对应的酒店
                QueryWrapper<HotelList> qw = new QueryWrapper<>();
                qw.eq("hotel_id",integerLongEntry.getKey());
                HotelList hotelList = hotelListMapper.selectOne(qw);
                list.add(hotelList);
                count++;
            }
        }
        return list;
    }

}
